package com.edou.base.token;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TokenInterceptor extends HandlerInterceptorAdapter {
	
	private Log logger = LogFactory.getLog(TokenInterceptor.class);

	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			TokenValidate annotation = method.getAnnotation(TokenValidate.class);
			if (annotation != null) {
				HttpSession session = request.getSession();
				if(isRepeatSubmit(request,annotation)){
					logger.debug("重复提交，访问路径：" + request.getRequestURI());
					session.removeAttribute(annotation.name());
					//判断请求方式
					String requestType = request.getHeader("X-Requested-With");
					if(StringUtils.isNotBlank(requestType) && StringUtils.equals("XMLHttpRequest", requestType)){
						//异步请求
						response.setContentType("text/json;charset=UTF-8");
						response.getWriter().write("{\"status\":\"error\",\"message\":\"请勿重复提交\"}");
					}else{
						response.sendRedirect(request.getContextPath() + "/repeatSubmit.htm");
					}
					return false;
				}
				session.removeAttribute(annotation.name());
			}
			return true;
		} else {
			return super.preHandle(request, response, handler);
		}
	}

	/**
	 * 是否重复提交
	 * @param request
	 * @return
	 */
	private boolean isRepeatSubmit(HttpServletRequest request,TokenValidate annotation) {
		String serverToken = (String) request.getSession().getAttribute(annotation.name());
		if (serverToken == null) {
			return true;
		}
		String clinetToken = request.getParameter(annotation.name());
		if (clinetToken == null) {
			return true;
		}
		if (!serverToken.equals(clinetToken)) {
			return true;
		}
		return false;
	}
	
}
